<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Circuit Data Integration Test</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .test-result {
            margin: 10px 0;
            padding: 10px;
            border-radius: 4px;
        }
        .success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .info {
            background-color: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        pre {
            background-color: #f8f9fa;
            padding: 10px;
            border-radius: 4px;
            overflow-x: auto;
        }
    </style>
</head>
<body>
    <h1>Circuit Data Integration Test</h1>
    <div id="results"></div>

    <script type="module">
        // Mock the data transformation functions for testing
        function transformCircuitData(jsonData) {
            const nodeMap = new Map();
            
            const nodes = jsonData.nodes.map((node) => {
                const getNodeColor = (featureType) => {
                    switch (featureType) {
                        case "logit": return "#ff6b6b";
                        case "embedding": return "#69b3a2";
                        case "cross layer transcoder": return "#4ecdc4";
                        default: return "#95a5a6";
                    }
                };

                const layerNum = parseInt(node.layer) || 0;
                const xPos = node.ctx_idx * 100 + 50;
                const yPos = layerNum * 80 + 50;

                const transformedNode = {
                    id: node.node_id,
                    nodeId: node.jsNodeId,
                    featureId: node.feature.toString(),
                    feature_type: node.feature_type,
                    ctx_idx: node.ctx_idx,
                    streamIdx: layerNum,
                    pos: [xPos, yPos],
                    xOffset: 0,
                    yOffset: 0,
                    nodeColor: getNodeColor(node.feature_type),
                    logitPct: node.token_prob,
                    logitToken: node.is_target_logit ? "target" : undefined,
                    localClerp: node.clerp,
                };

                nodeMap.set(node.jsNodeId, transformedNode);
                return transformedNode;
            });

            // Extract edges from the root level of the JSON
            const edges = Object.values(jsonData).filter((value) => {
              return typeof value === 'object' && value !== null && 'source' in value && 'target' in value && 'weight' in value;
            });
            
            const links = edges.map((edge) => {
                const sourceNode = nodeMap.get(edge.source);
                const targetNode = nodeMap.get(edge.target);
                
                if (!sourceNode || !targetNode) {
                    console.warn(`Missing node for edge: ${edge.source} -> ${edge.target}`);
                    return null;
                }

                const strokeWidth = Math.max(0.5, Math.min(3, Math.abs(edge.weight) * 10));
                const color = edge.weight > 0 ? "#4CAF50" : "#F44336";

                return {
                    source: edge.source,
                    target: edge.target,
                    sourceNode,
                    targetNode,
                    pathStr: `M${sourceNode.pos[0]},${sourceNode.pos[1]}L${targetNode.pos[0]},${targetNode.pos[1]}`,
                    color,
                    strokeWidth,
                };
            }).filter(Boolean);

            return {
                nodes,
                links,
                metadata: {
                    prompt_tokens: jsonData.metadata.prompt_tokens,
                },
                byStream: [],
            };
        }

        async function testIntegration() {
            const resultsDiv = document.getElementById('results');
            
            function addResult(message, type = 'info') {
                const div = document.createElement('div');
                div.className = `test-result ${type}`;
                div.innerHTML = message;
                resultsDiv.appendChild(div);
            }

            try {
                addResult('<h3>Testing JSON file loading...</h3>', 'info');
                
                const response = await fetch('/circuits/example_data/capital-state-dallas.json');
                if (!response.ok) {
                    throw new Error(`Failed to load circuit data: ${response.statusText}`);
                }
                
                addResult('<strong>✓</strong> JSON file loaded successfully', 'success');
                
                const jsonData = await response.json();
                
                // Count edges at the root level
                const edgeCount = Object.values(jsonData).filter(value => 
                  typeof value === 'object' && value !== null && 'source' in value && 'target' in value && 'weight' in value
                ).length;
                
                addResult(`<strong>✓</strong> JSON parsed successfully. Found ${jsonData.nodes.length} nodes and ${edgeCount} edges`, 'success');
                
                addResult('<h3>Testing data transformation...</h3>', 'info');
                
                const transformedData = transformCircuitData(jsonData);
                addResult(`<strong>✓</strong> Data transformation successful. Transformed to ${transformedData.nodes.length} nodes and ${transformedData.links.length} links`, 'success');
                
                addResult('<h3>Sample transformed data:</h3>', 'info');
                addResult(`<pre>${JSON.stringify(transformedData.nodes.slice(0, 3), null, 2)}</pre>`, 'info');
                
                addResult('<h3>Metadata:</h3>', 'info');
                addResult(`<strong>Prompt:</strong> ${jsonData.metadata.prompt}<br><strong>Tokens:</strong> ${jsonData.metadata.prompt_tokens.join(' ')}`, 'info');
                
            } catch (error) {
                addResult(`<strong>✗</strong> Error: ${error.message}`, 'error');
                console.error('Integration test failed:', error);
            }
        }

        // Run the test when the page loads
        testIntegration();
    </script>
</body>
</html> 